<template>
  <div class="mario-game-container">
    <div class="game-header">
      <h1>超级玛丽</h1>
      <div class="game-stats">
        <div class="stat">
          <span class="stat-icon">🍄</span>
          <span class="stat-value">{{ lives }}</span>
        </div>
        <div class="stat">
          <span class="stat-icon">🪙</span>
          <span class="stat-value">{{ coins }}</span>
        </div>
        <div class="stat">
          <span class="stat-icon">⏱️</span>
          <span class="stat-value">{{ time }}</span>
        </div>
        <div class="stat">
          <span class="stat-icon">🏁</span>
          <span class="stat-value">{{ currentLevel }}/{{ totalLevels }}</span>
        </div>
      </div>
    </div>

    <div class="game-canvas-container">
      <canvas ref="gameCanvas" width="800" height="400"></canvas>
      
      <div v-if="!gameStarted" class="game-overlay">
        <div class="game-menu">
          <h2>超级玛丽</h2>
          <p>使用方向键移动，空格键跳跃</p>
          <button @click="startGame" class="start-button">开始游戏</button>
        </div>
      </div>
      
      <div v-if="gameOver" class="game-overlay">
        <div class="game-menu">
          <h2>{{ currentLevel > totalLevels ? '恭喜通关!' : '游戏结束' }}</h2>
          <p>得分: {{ coins }}</p>
          <p v-if="currentLevel > totalLevels">你成功完成了所有关卡!</p>
          <button @click="restartGame" class="start-button">{{ currentLevel > totalLevels ? '再玩一次' : '重新开始' }}</button>
        </div>
      </div>
    </div>

    <div class="game-controls">
      <div class="mobile-controls">
        <div class="direction-controls">
          <button @touchstart="handleMobileControl('left', true)" @touchend="handleMobileControl('left', false)" class="control-button left">
            <span>←</span>
          </button>
          <button @touchstart="handleMobileControl('right', true)" @touchend="handleMobileControl('right', false)" class="control-button right">
            <span>→</span>
          </button>
        </div>
        <button @touchstart="handleMobileControl('jump', true)" @touchend="handleMobileControl('jump', false)" class="control-button jump">
          <span>跳跃</span>
        </button>
      </div>
    </div>

    <div class="game-instructions">
      <h3>游戏说明</h3>
      <p>控制玛丽奥在关卡中移动，收集金币，踩扁敌人，到达终点旗杆。</p>
      <ul>
        <li><strong>方向键左右</strong>: 移动玛丽奥</li>
        <li><strong>空格键</strong>: 跳跃</li>
        <li><strong>收集金币</strong>: 增加分数</li>
        <li><strong>收集宝石</strong>: 获得更多分数</li>
        <li><strong>踩扁敌人</strong>: 消灭敌人</li>
        <li><strong>碰到敌人</strong>: 失去生命</li>
        <li><strong>碰到熔岩</strong>: 失去生命</li>
        <li><strong>到达旗杆</strong>: 完成关卡</li>
      </ul>
      
      <h4>关卡说明</h4>
      <ul>
        <li><strong>关卡1</strong>: 入门级难度，适合新手熟悉游戏操作</li>
        <li><strong>关卡2</strong>: 中等难度，平台间距更大，敌人更多</li>
        <li><strong>关卡3</strong>: 高难度，平台更小更分散，敌人移动更快</li>
        <li><strong>关卡4</strong>: 地下洞穴，有垂直移动的蝙蝠敌人和宝石</li>
        <li><strong>关卡5</strong>: 城堡最终关卡，有熔岩和最终BOSS</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

// 游戏状态
const gameCanvas = ref(null);
const gameStarted = ref(false);
const gameOver = ref(false);
const lives = ref(3);
const coins = ref(0);
const time = ref(300);
const currentLevel = ref(1);
const totalLevels = 5;

// 游戏对象
let ctx;
let animationFrameId;
let lastTimestamp = 0;
let mario;
let platforms = [];
let enemies = [];
let coinItems = [];
let backgroundImage;
let marioSprite;
let enemySprite;
let coinSprite;
let platformSprite;
let flagSprite;
let finishFlag;

// 控制状态
const keys = {
  left: false,
  right: false,
  jump: false
};

// 游戏常量
const GRAVITY = 0.5;
const JUMP_FORCE = -12;
const MARIO_SPEED = 5;
const ENEMY_SPEED = 2;

// 开始游戏
const startGame = () => {
  gameStarted.value = true;
  gameOver.value = false;
  lives.value = 3;
  coins.value = 0;
  time.value = 300;
  currentLevel.value = 1;
  
  initGame();
  startGameLoop();
  startTimer();
};

// 重新开始游戏
const restartGame = () => {
  startGame();
};

// 初始化游戏
const initGame = () => {
  const canvas = gameCanvas.value;
  ctx = canvas.getContext('2d');
  
  // 加载图片资源
  loadImages();
  
  // 创建玛丽奥
  mario = {
    x: 50,
    y: 300,
    width: 40,
    height: 60,
    velocityX: 0,
    velocityY: 0,
    isJumping: false,
    direction: 'right'
  };
  
  // 创建平台
  createLevel();
};

// 加载图片资源
const loadImages = () => {
  // 这里应该加载实际的图片，为了简化，我们使用颜色代替
  backgroundImage = new Image();
  backgroundImage.src = '';
  
  marioSprite = new Image();
  enemySprite = new Image();
  coinSprite = new Image();
  platformSprite = new Image();
  flagSprite = new Image();
};

// 创建关卡
const createLevel = () => {
  // 根据当前关卡创建不同的游戏元素
  platforms = [];
  enemies = [];
  coinItems = [];
  
  // 基础地面平台（所有关卡都有）
  platforms.push({ x: 0, y: 360, width: 800, height: 40 });
  
  switch(currentLevel.value) {
    case 1:
      createLevel1();
      break;
    case 2:
      createLevel2();
      break;
    case 3:
      createLevel3();
      break;
    case 4:
      createLevel4();
      break;
    case 5:
      createLevel5();
      break;
    default:
      createLevel1();
  }
  
  // 创建终点旗杆
  finishFlag = { x: 750, y: 160, width: 30, height: 200 };
};

// 关卡1 - 简单入门关卡
const createLevel1 = () => {
  // 平台
  platforms.push(
    { x: 200, y: 300, width: 100, height: 20 },
    { x: 350, y: 250, width: 100, height: 20 },
    { x: 500, y: 200, width: 100, height: 20 },
    { x: 650, y: 250, width: 100, height: 20 }
  );
  
  // 敌人
  enemies.push(
    { x: 300, y: 320, width: 40, height: 40, direction: -1 },
    { x: 600, y: 320, width: 40, height: 40, direction: -1 }
  );
  
  // 金币
  coinItems.push(
    { x: 220, y: 260, width: 20, height: 20, collected: false },
    { x: 260, y: 260, width: 20, height: 20, collected: false },
    { x: 380, y: 210, width: 20, height: 20, collected: false },
    { x: 420, y: 210, width: 20, height: 20, collected: false },
    { x: 530, y: 160, width: 20, height: 20, collected: false },
    { x: 570, y: 160, width: 20, height: 20, collected: false },
    { x: 680, y: 210, width: 20, height: 20, collected: false },
    { x: 720, y: 210, width: 20, height: 20, collected: false }
  );
};

// 关卡2 - 中等难度关卡
const createLevel2 = () => {
  // 平台 - 更复杂的布局
  platforms.push(
    { x: 120, y: 320, width: 60, height: 20 },
    { x: 240, y: 280, width: 60, height: 20 },
    { x: 350, y: 240, width: 60, height: 20 },
    { x: 460, y: 200, width: 60, height: 20 },
    { x: 570, y: 240, width: 60, height: 20 },
    { x: 680, y: 280, width: 60, height: 20 },
    { x: 200, y: 180, width: 100, height: 20 },
    { x: 500, y: 120, width: 100, height: 20 }
  );
  
  // 更多敌人
  enemies.push(
    { x: 180, y: 320, width: 40, height: 40, direction: -1 },
    { x: 400, y: 320, width: 40, height: 40, direction: 1 },
    { x: 600, y: 320, width: 40, height: 40, direction: -1 },
    { x: 250, y: 140, width: 40, height: 40, direction: 1 }
  );
  
  // 更多金币，一些放在高处
  coinItems.push(
    { x: 140, y: 280, width: 20, height: 20, collected: false },
    { x: 260, y: 240, width: 20, height: 20, collected: false },
    { x: 370, y: 200, width: 20, height: 20, collected: false },
    { x: 480, y: 160, width: 20, height: 20, collected: false },
    { x: 590, y: 200, width: 20, height: 20, collected: false },
    { x: 700, y: 240, width: 20, height: 20, collected: false },
    { x: 220, y: 140, width: 20, height: 20, collected: false },
    { x: 260, y: 140, width: 20, height: 20, collected: false },
    { x: 520, y: 80, width: 20, height: 20, collected: false },
    { x: 560, y: 80, width: 20, height: 20, collected: false },
    { x: 300, y: 280, width: 20, height: 20, collected: false },
    { x: 500, y: 280, width: 20, height: 20, collected: false }
  );
};

// 关卡3 - 高难度关卡
const createLevel3 = () => {
  // 平台 - 更加复杂和具有挑战性
  platforms.push(
    { x: 100, y: 320, width: 40, height: 20 },
    { x: 200, y: 280, width: 40, height: 20 },
    { x: 300, y: 240, width: 40, height: 20 },
    { x: 400, y: 200, width: 40, height: 20 },
    { x: 500, y: 240, width: 40, height: 20 },
    { x: 600, y: 280, width: 40, height: 20 },
    { x: 700, y: 320, width: 40, height: 20 },
    { x: 150, y: 200, width: 30, height: 20 },
    { x: 250, y: 160, width: 30, height: 20 },
    { x: 350, y: 120, width: 30, height: 20 },
    { x: 450, y: 160, width: 30, height: 20 },
    { x: 550, y: 200, width: 30, height: 20 },
    { x: 650, y: 240, width: 30, height: 20 }
  );
  
  // 更多敌人，移动更快
  for (let i = 0; i < 5; i++) {
    enemies.push({
      x: 150 + i * 120,
      y: 320,
      width: 40,
      height: 40,
      direction: i % 2 === 0 ? -1 : 1,
      speed: 3 // 更快的敌人
    });
  }
  
  // 在高处添加敌人
  enemies.push(
    { x: 200, y: 120, width: 40, height: 40, direction: 1, speed: 2 },
    { x: 500, y: 120, width: 40, height: 40, direction: -1, speed: 2 }
  );
  
  // 更多金币，一些放在难以到达的位置
  for (let i = 0; i < 8; i++) {
    coinItems.push({
      x: 120 + i * 80,
      y: 280 - (i % 3) * 40,
      width: 20,
      height: 20,
      collected: false
    });
  }
  
  // 额外的奖励金币
  coinItems.push(
    { x: 350, y: 80, width: 20, height: 20, collected: false },
    { x: 380, y: 80, width: 20, height: 20, collected: false },
    { x: 410, y: 80, width: 20, height: 20, collected: false },
    { x: 150, y: 160, width: 20, height: 20, collected: false },
    { x: 650, y: 200, width: 20, height: 20, collected: false }
  );
};

// 关卡4 - 地下洞穴关卡
const createLevel4 = () => {
  // 洞穴平台布局
  platforms.push(
    // 主要平台
    { x: 100, y: 300, width: 150, height: 20 },
    { x: 320, y: 300, width: 150, height: 20 },
    { x: 540, y: 300, width: 150, height: 20 },
    
    // 上层平台
    { x: 200, y: 200, width: 100, height: 20 },
    { x: 400, y: 150, width: 100, height: 20 },
    { x: 600, y: 200, width: 100, height: 20 },
    
    // 小平台
    { x: 300, y: 250, width: 40, height: 20 },
    { x: 500, y: 250, width: 40, height: 20 }
  );
  
  // 洞穴敌人 - 蝙蝠类型，移动模式不同
  enemies.push(
    // 水平移动的敌人
    { x: 150, y: 260, width: 40, height: 40, direction: 1, speed: 2 },
    { x: 400, y: 260, width: 40, height: 40, direction: -1, speed: 2 },
    { x: 600, y: 260, width: 40, height: 40, direction: 1, speed: 2 },
    
    // 垂直移动的敌人（特殊类型）
    { 
      x: 250, 
      y: 150, 
      width: 40, 
      height: 40, 
      direction: 1, 
      speed: 1.5,
      verticalMovement: true,
      verticalDirection: 1,
      minY: 100,
      maxY: 250
    },
    { 
      x: 500, 
      y: 100, 
      width: 40, 
      height: 40, 
      direction: -1, 
      speed: 1.5,
      verticalMovement: true,
      verticalDirection: 1,
      minY: 80,
      maxY: 200
    }
  );
  
  // 洞穴中的宝石（比金币更值钱）
  for (let i = 0; i < 10; i++) {
    coinItems.push({
      x: 120 + i * 70,
      y: 100 + (i % 3) * 50,
      width: 25,
      height: 25,
      collected: false,
      isGem: true,
      value: 3 // 宝石价值3个金币
    });
  }
  
  // 隐藏的金币
  coinItems.push(
    { x: 220, y: 160, width: 20, height: 20, collected: false },
    { x: 240, y: 160, width: 20, height: 20, collected: false },
    { x: 420, y: 110, width: 20, height: 20, collected: false },
    { x: 440, y: 110, width: 20, height: 20, collected: false },
    { x: 460, y: 110, width: 20, height: 20, collected: false },
    { x: 620, y: 160, width: 20, height: 20, collected: false },
    { x: 640, y: 160, width: 20, height: 20, collected: false }
  );
};

// 关卡5 - 城堡最终关卡
const createLevel5 = () => {
  // 城堡平台布局 - 更复杂的结构
  platforms.push(
    // 主要平台
    { x: 100, y: 320, width: 100, height: 20 },
    { x: 250, y: 320, width: 100, height: 20 },
    { x: 400, y: 320, width: 100, height: 20 },
    { x: 550, y: 320, width: 100, height: 20 },
    
    // 中层平台
    { x: 150, y: 250, width: 80, height: 20 },
    { x: 300, y: 250, width: 80, height: 20 },
    { x: 450, y: 250, width: 80, height: 20 },
    { x: 600, y: 250, width: 80, height: 20 },
    
    // 上层平台
    { x: 200, y: 180, width: 60, height: 20 },
    { x: 350, y: 180, width: 60, height: 20 },
    { x: 500, y: 180, width: 60, height: 20 },
    
    // 最上层平台
    { x: 250, y: 110, width: 40, height: 20 },
    { x: 400, y: 110, width: 40, height: 20 },
    { x: 550, y: 110, width: 40, height: 20 }
  );
  
  // 添加熔岩池（碰到会立即失去生命）
  for (let i = 0; i < 8; i++) {
    enemies.push({
      x: 100 + i * 80,
      y: 340,
      width: 60,
      height: 20,
      isLava: true,
      direction: 0,
      speed: 0
    });
  }
  
  // 最终BOSS敌人 - 更大、更强
  enemies.push({
    x: 600, 
    y: 200, 
    width: 60, 
    height: 60, 
    direction: -1, 
    speed: 3,
    isBoss: true,
    health: 3 // 需要踩3次才能消灭
  });
  
  // 普通敌人
  enemies.push(
    { x: 150, y: 280, width: 40, height: 40, direction: 1, speed: 2.5 },
    { x: 350, y: 280, width: 40, height: 40, direction: -1, speed: 2.5 },
    { x: 500, y: 280, width: 40, height: 40, direction: 1, speed: 2.5 },
    { x: 250, y: 210, width: 40, height: 40, direction: -1, speed: 2.5 },
    { x: 400, y: 210, width: 40, height: 40, direction: 1, speed: 2.5 }
  );
  
  // 城堡中的金币和宝石
  for (let i = 0; i < 5; i++) {
    // 金币
    coinItems.push({
      x: 120 + i * 150,
      y: 220,
      width: 20,
      height: 20,
      collected: false
    });
    
    // 宝石
    coinItems.push({
      x: 180 + i * 150,
      y: 150,
      width: 25,
      height: 25,
      collected: false,
      isGem: true,
      value: 5 // 最终关卡宝石价值更高
    });
  }
  
  // 隐藏的奖励金币
  coinItems.push(
    { x: 270, y: 80, width: 20, height: 20, collected: false },
    { x: 420, y: 80, width: 20, height: 20, collected: false },
    { x: 570, y: 80, width: 20, height: 20, collected: false }
  );
};

// 游戏循环
const startGameLoop = () => {
  const gameLoop = (timestamp) => {
    if (!lastTimestamp) lastTimestamp = timestamp;
    const deltaTime = timestamp - lastTimestamp;
    lastTimestamp = timestamp;
    
    // 清除画布
    ctx.clearRect(0, 0, gameCanvas.value.width, gameCanvas.value.height);
    
    // 绘制背景
    ctx.fillStyle = '#87CEEB'; // 天空蓝
    ctx.fillRect(0, 0, gameCanvas.value.width, gameCanvas.value.height);
    
    // 更新游戏状态
    updateMario();
    updateEnemies();
    checkCollisions();
    
    // 绘制游戏对象
    drawPlatforms();
    drawCoins();
    drawEnemies();
    drawMario();
    drawFinishFlag();
    drawLevelInfo();
    
    // 继续游戏循环
    if (gameStarted.value && !gameOver.value) {
      animationFrameId = requestAnimationFrame(gameLoop);
    }
  };
  
  animationFrameId = requestAnimationFrame(gameLoop);
};

// 更新玛丽奥
const updateMario = () => {
  // 水平移动
  mario.velocityX = 0;
  if (keys.left) {
    mario.velocityX = -MARIO_SPEED;
    mario.direction = 'left';
  }
  if (keys.right) {
    mario.velocityX = MARIO_SPEED;
    mario.direction = 'right';
  }
  
  // 跳跃
  if (keys.jump && !mario.isJumping) {
    mario.velocityY = JUMP_FORCE;
    mario.isJumping = true;
  }
  
  // 应用重力
  mario.velocityY += GRAVITY;
  
  // 更新位置
  mario.x += mario.velocityX;
  mario.y += mario.velocityY;
  
  // 边界检查
  if (mario.x < 0) mario.x = 0;
  if (mario.x + mario.width > gameCanvas.value.width) {
    mario.x = gameCanvas.value.width - mario.width;
  }
  
  // 平台碰撞检测
  let onPlatform = false;
  for (const platform of platforms) {
    if (
      mario.x + mario.width > platform.x &&
      mario.x < platform.x + platform.width &&
      mario.y + mario.height > platform.y &&
      mario.y + mario.height < platform.y + platform.height / 2 &&
      mario.velocityY > 0
    ) {
      mario.y = platform.y - mario.height;
      mario.velocityY = 0;
      mario.isJumping = false;
      onPlatform = true;
    }
  }
  
  // 如果不在平台上，则处于跳跃状态
  if (!onPlatform && mario.velocityY === 0) {
    mario.isJumping = true;
  }
  
  // 检查是否掉出屏幕
  if (mario.y > gameCanvas.value.height) {
    loseLife();
  }
};

// 更新敌人
const updateEnemies = () => {
  for (const enemy of enemies) {
    // 跳过熔岩（不移动）
    if (enemy.isLava) continue;
    
    // 使用敌人的速度属性，如果没有则使用默认值
    const speed = enemy.speed || ENEMY_SPEED;
    
    // 处理垂直移动的敌人
    if (enemy.verticalMovement) {
      enemy.y += enemy.verticalDirection * speed;
      
      // 检查垂直边界
      if (enemy.y <= enemy.minY) {
        enemy.verticalDirection = 1;
      } else if (enemy.y >= enemy.maxY) {
        enemy.verticalDirection = -1;
      }
    } else {
      // 水平移动的敌人
      enemy.x += enemy.direction * speed;
    }
    
    // 敌人碰到边界时改变方向
    for (const platform of platforms) {
      if (
        enemy.x + enemy.width > platform.x + platform.width ||
        enemy.x < platform.x
      ) {
        if (
          enemy.y + enemy.height > platform.y &&
          enemy.y < platform.y + platform.height &&
          Math.abs(enemy.x - platform.x) < 10 || 
          Math.abs(enemy.x + enemy.width - platform.x - platform.width) < 10
        ) {
          enemy.direction *= -1;
        }
      }
    }
  }
};

// 检查碰撞
const checkCollisions = () => {
  // 检查与敌人的碰撞
  for (let i = 0; i < enemies.length; i++) {
    const enemy = enemies[i];
    
    if (
      mario.x + mario.width > enemy.x &&
      mario.x < enemy.x + enemy.width &&
      mario.y + mario.height > enemy.y &&
      mario.y < enemy.y + enemy.height
    ) {
      // 处理熔岩碰撞
      if (enemy.isLava) {
        loseLife();
        continue;
      }
      
      // 从上方踩敌人
      if (
        mario.velocityY > 0 &&
        mario.y + mario.height < enemy.y + enemy.height / 2
      ) {
        // 处理BOSS敌人
        if (enemy.isBoss) {
          enemy.health--;
          mario.velocityY = JUMP_FORCE / 1.2; // 弹得更高
          
          // 只有当生命值为0时才消灭BOSS
          if (enemy.health <= 0) {
            enemies.splice(i, 1);
            coins.value += 20; // BOSS奖励
          }
        } else {
          // 普通敌人
          enemies.splice(i, 1);
          mario.velocityY = JUMP_FORCE / 1.5;
          coins.value += 5;
        }
      } else {
        // 被敌人碰到
        loseLife();
      }
    }
  }
  
  // 检查与金币的碰撞
  for (let i = 0; i < coinItems.length; i++) {
    const coin = coinItems[i];
    
    if (
      !coin.collected &&
      mario.x + mario.width > coin.x &&
      mario.x < coin.x + coin.width &&
      mario.y + mario.height > coin.y &&
      mario.y < coin.y + coin.height
    ) {
      coin.collected = true;
      // 如果是宝石，给予更多分数
      if (coin.isGem) {
        coins.value += coin.value || 3;
      } else {
        coins.value += 1;
      }
    }
  }
  
  // 检查与终点旗杆的碰撞
  if (
    mario.x + mario.width > finishFlag.x &&
    mario.x < finishFlag.x + finishFlag.width &&
    mario.y + mario.height > finishFlag.y
  ) {
    winLevel();
  }
};

// 失去生命
const loseLife = () => {
  lives.value--;
  
  if (lives.value <= 0) {
    endGame();
  } else {
    // 重置玛丽奥位置
    mario.x = 50;
    mario.y = 300;
    mario.velocityX = 0;
    mario.velocityY = 0;
  }
};

// 赢得关卡
const winLevel = () => {
  // 添加时间奖励
  coins.value += time.value;
  
  // 检查是否还有下一关
  if (currentLevel.value < totalLevels) {
    // 进入下一关
    currentLevel.value++;
    time.value = 300; // 重置时间
    
    // 重置玛丽奥位置
    mario.x = 50;
    mario.y = 300;
    mario.velocityX = 0;
    mario.velocityY = 0;
    
    // 创建新关卡
    createLevel();
    
    // 显示过关信息
    showLevelComplete();
  } else {
    // 通关游戏
    endGame(true);
  }
};

// 显示过关信息
const showLevelComplete = () => {
  // 暂停游戏
  cancelAnimationFrame(animationFrameId);
  
  // 在画布上显示过关信息
  ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
  ctx.fillRect(0, 0, gameCanvas.value.width, gameCanvas.value.height);
  
  ctx.fillStyle = 'white';
  ctx.font = '30px Arial';
  ctx.textAlign = 'center';
  ctx.fillText(`关卡 ${currentLevel.value - 1} 完成!`, gameCanvas.value.width / 2, gameCanvas.value.height / 2 - 30);
  ctx.fillText(`得分: ${coins.value}`, gameCanvas.value.width / 2, gameCanvas.value.height / 2 + 10);
  ctx.fillText(`准备进入关卡 ${currentLevel.value}...`, gameCanvas.value.width / 2, gameCanvas.value.height / 2 + 50);
  
  // 3秒后继续游戏
  setTimeout(() => {
    startGameLoop();
  }, 3000);
};

// 结束游戏
const endGame = (win = false) => {
  gameStarted.value = false;
  gameOver.value = true;
  cancelAnimationFrame(animationFrameId);
};

// 计时器
const startTimer = () => {
  const timerInterval = setInterval(() => {
    if (gameStarted.value && !gameOver.value) {
      time.value--;
      
      if (time.value <= 0) {
        loseLife();
        clearInterval(timerInterval);
      }
    } else {
      clearInterval(timerInterval);
    }
  }, 1000);
};

// 绘制玛丽奥
const drawMario = () => {
  ctx.fillStyle = 'red';
  ctx.fillRect(mario.x, mario.y, mario.width, mario.height);
  
  // 绘制帽子
  ctx.fillStyle = 'red';
  ctx.fillRect(mario.x - 5, mario.y - 10, mario.width + 10, 10);
  
  // 绘制脸
  ctx.fillStyle = 'tan';
  ctx.fillRect(mario.x + 5, mario.y, mario.width - 10, 20);
  
  // 绘制眼睛
  ctx.fillStyle = 'white';
  if (mario.direction === 'right') {
    ctx.fillRect(mario.x + 25, mario.y + 5, 8, 8);
    ctx.fillStyle = 'black';
    ctx.fillRect(mario.x + 28, mario.y + 8, 4, 4);
  } else {
    ctx.fillRect(mario.x + 7, mario.y + 5, 8, 8);
    ctx.fillStyle = 'black';
    ctx.fillRect(mario.x + 8, mario.y + 8, 4, 4);
  }
  
  // 绘制胡子
  ctx.fillStyle = 'black';
  ctx.fillRect(mario.x + 10, mario.y + 15, 20, 3);
  
  // 绘制衣服
  ctx.fillStyle = 'blue';
  ctx.fillRect(mario.x, mario.y + 20, mario.width, mario.height - 20);
};

// 绘制平台
const drawPlatforms = () => {
  ctx.fillStyle = 'green';
  for (const platform of platforms) {
    ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
    
    // 绘制草地纹理
    ctx.fillStyle = '#8B4513'; // 棕色土壤
    ctx.fillRect(platform.x, platform.y + 5, platform.width, platform.height - 5);
    
    ctx.fillStyle = 'green';
  }
};

// 绘制敌人
const drawEnemies = () => {
  for (const enemy of enemies) {
    // 绘制熔岩
    if (enemy.isLava) {
      // 绘制熔岩池
      const gradient = ctx.createLinearGradient(enemy.x, enemy.y, enemy.x, enemy.y + enemy.height);
      gradient.addColorStop(0, '#ff5722');
      gradient.addColorStop(1, '#bf360c');
      ctx.fillStyle = gradient;
      ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
      
      // 绘制熔岩泡泡
      ctx.fillStyle = '#ffab91';
      ctx.beginPath();
      ctx.arc(enemy.x + 10, enemy.y + 5, 3, 0, Math.PI * 2);
      ctx.fill();
      ctx.beginPath();
      ctx.arc(enemy.x + 30, enemy.y + 8, 2, 0, Math.PI * 2);
      ctx.fill();
      ctx.beginPath();
      ctx.arc(enemy.x + 50, enemy.y + 6, 4, 0, Math.PI * 2);
      ctx.fill();
      
      continue;
    }
    
    // 绘制BOSS敌人
    if (enemy.isBoss) {
      // 绘制BOSS身体
      ctx.fillStyle = '#d32f2f';
      ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
      
      // 绘制BOSS眼睛
      ctx.fillStyle = 'white';
      ctx.fillRect(enemy.x + 10, enemy.y + 10, 15, 15);
      ctx.fillRect(enemy.x + enemy.width - 25, enemy.y + 10, 15, 15);
      
      ctx.fillStyle = 'black';
      ctx.fillRect(enemy.x + 15, enemy.y + 15, 5, 5);
      ctx.fillRect(enemy.x + enemy.width - 20, enemy.y + 15, 5, 5);
      
      // 绘制BOSS嘴巴
      ctx.fillStyle = 'black';
      ctx.fillRect(enemy.x + 15, enemy.y + 40, enemy.width - 30, 5);
      
      // 绘制BOSS角
      ctx.fillStyle = '#d32f2f';
      ctx.beginPath();
      ctx.moveTo(enemy.x + 10, enemy.y);
      ctx.lineTo(enemy.x + 20, enemy.y - 15);
      ctx.lineTo(enemy.x + 30, enemy.y);
      ctx.fill();
      
      ctx.beginPath();
      ctx.moveTo(enemy.x + enemy.width - 30, enemy.y);
      ctx.lineTo(enemy.x + enemy.width - 20, enemy.y - 15);
      ctx.lineTo(enemy.x + enemy.width - 10, enemy.y);
      ctx.fill();
      
      // 绘制BOSS生命值
      ctx.fillStyle = '#4caf50';
      ctx.fillRect(enemy.x, enemy.y - 10, (enemy.width / 3) * enemy.health, 5);
      
      continue;
    }
    
    // 绘制普通敌人
    ctx.fillStyle = 'brown';
    ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
    
    // 绘制眼睛
    ctx.fillStyle = 'white';
    ctx.fillRect(enemy.x + 5, enemy.y + 5, 10, 10);
    ctx.fillRect(enemy.x + enemy.width - 15, enemy.y + 5, 10, 10);
    
    ctx.fillStyle = 'black';
    ctx.fillRect(enemy.x + 8, enemy.y + 8, 4, 4);
    ctx.fillRect(enemy.x + enemy.width - 12, enemy.y + 8, 4, 4);
    
    // 如果是垂直移动的敌人（蝙蝠），添加翅膀
    if (enemy.verticalMovement) {
      ctx.fillStyle = '#795548';
      
      // 左翅膀
      ctx.beginPath();
      ctx.moveTo(enemy.x, enemy.y + enemy.height/2);
      ctx.lineTo(enemy.x - 15, enemy.y + 10);
      ctx.lineTo(enemy.x - 5, enemy.y + enemy.height - 10);
      ctx.fill();
      
      // 右翅膀
      ctx.beginPath();
      ctx.moveTo(enemy.x + enemy.width, enemy.y + enemy.height/2);
      ctx.lineTo(enemy.x + enemy.width + 15, enemy.y + 10);
      ctx.lineTo(enemy.x + enemy.width + 5, enemy.y + enemy.height - 10);
      ctx.fill();
    }
  }
};

// 绘制金币
const drawCoins = () => {
  for (const coin of coinItems) {
    if (!coin.collected) {
      if (coin.isGem) {
        // 绘制宝石
        ctx.fillStyle = '#2196f3'; // 蓝色宝石
        ctx.beginPath();
        ctx.moveTo(coin.x, coin.y + coin.height/2);
        ctx.lineTo(coin.x + coin.width/2, coin.y);
        ctx.lineTo(coin.x + coin.width, coin.y + coin.height/2);
        ctx.lineTo(coin.x + coin.width/2, coin.y + coin.height);
        ctx.closePath();
        ctx.fill();
        
        // 宝石光泽
        ctx.fillStyle = 'rgba(255, 255, 255, 0.6)';
        ctx.beginPath();
        ctx.moveTo(coin.x + coin.width/4, coin.y + coin.height/4);
        ctx.lineTo(coin.x + coin.width/2, coin.y + coin.height/3);
        ctx.lineTo(coin.x + coin.width/4, coin.y + coin.height/2);
        ctx.closePath();
        ctx.fill();
      } else {
        // 绘制普通金币
        ctx.fillStyle = 'gold';
        ctx.beginPath();
        ctx.arc(coin.x + coin.width / 2, coin.y + coin.height / 2, coin.width / 2, 0, Math.PI * 2);
        ctx.fill();
      }
    }
  }
};

// 绘制终点旗杆
const drawFinishFlag = () => {
  // 绘制旗杆
  ctx.fillStyle = 'gray';
  ctx.fillRect(finishFlag.x, finishFlag.y, 5, finishFlag.height);
  
  // 绘制旗帜
  ctx.fillStyle = 'red';
  ctx.beginPath();
  ctx.moveTo(finishFlag.x + 5, finishFlag.y);
  ctx.lineTo(finishFlag.x + 5, finishFlag.y + 40);
  ctx.lineTo(finishFlag.x + 30, finishFlag.y + 20);
  ctx.closePath();
  ctx.fill();
};

// 绘制关卡信息
const drawLevelInfo = () => {
  ctx.fillStyle = 'white';
  ctx.font = '16px Arial';
  ctx.textAlign = 'left';
  ctx.fillText(`关卡: ${currentLevel.value}/${totalLevels}`, 10, 20);
};

// 键盘事件处理
const handleKeyDown = (e) => {
  if (!gameStarted.value) return;
  
  if (e.key === 'ArrowLeft') keys.left = true;
  if (e.key === 'ArrowRight') keys.right = true;
  if (e.key === ' ' || e.key === 'ArrowUp') keys.jump = true;
};

const handleKeyUp = (e) => {
  if (e.key === 'ArrowLeft') keys.left = false;
  if (e.key === 'ArrowRight') keys.right = false;
  if (e.key === ' ' || e.key === 'ArrowUp') keys.jump = false;
};

// 移动端控制
const handleMobileControl = (control, isPressed) => {
  if (!gameStarted.value) return;
  keys[control] = isPressed;
};

// 组件挂载和卸载
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown);
  window.addEventListener('keyup', handleKeyUp);
});

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown);
  window.removeEventListener('keyup', handleKeyUp);
  cancelAnimationFrame(animationFrameId);
});
</script>

<style scoped>
.mario-game-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 20px;
}

.game-header h1 {
  margin: 0;
  color: #e53935;
  font-size: 28px;
  text-shadow: 2px 2px 0 #ffeb3b;
}

.game-stats {
  display: flex;
  gap: 20px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 18px;
  font-weight: bold;
}

.stat-icon {
  font-size: 24px;
}

.game-canvas-container {
  position: relative;
  width: 100%;
  border: 4px solid #4caf50;
  border-radius: 8px;
  overflow: hidden;
}

canvas {
  display: block;
  background-color: #87CEEB;
}

.game-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
}

.game-menu {
  background-color: #fff;
  padding: 30px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
}

.game-menu h2 {
  color: #e53935;
  margin-top: 0;
  font-size: 24px;
}

.start-button {
  background-color: #4caf50;
  color: white;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 20px;
  transition: background-color 0.3s;
}

.start-button:hover {
  background-color: #388e3c;
}

.game-controls {
  width: 100%;
  margin-top: 20px;
}

.mobile-controls {
  display: none;
}

.game-instructions {
  margin-top: 30px;
  width: 100%;
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
}

.game-instructions h3 {
  margin-top: 0;
  color: #333;
}

.game-instructions ul {
  padding-left: 20px;
}

.game-instructions li {
  margin-bottom: 8px;
}

/* 移动端样式 */
@media (max-width: 768px) {
  .mobile-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }
  
  .direction-controls {
    display: flex;
    gap: 10px;
  }
  
  .control-button {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    font-size: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
  
  .control-button.jump {
    width: 100px;
    border-radius: 30px;
    font-size: 18px;
  }
}

/* 暗色主题 */
@media (prefers-color-scheme: dark) {
  .game-instructions {
    background-color: #333;
    color: #f5f5f5;
  }
  
  .game-instructions h3 {
    color: #f5f5f5;
  }
  
  .game-menu {
    background-color: #333;
    color: #f5f5f5;
  }
  
  .game-menu h2 {
    color: #ff6b6b;
  }
}
</style> 